//
//  ContentView.swift
//  ClassManager
//
//  Created by wqh on 1/27/21.
//

import SwiftUI
import CoreBluetooth

var unlockTime: TimeInterval = 0
var BLEName = ""

struct ContentView: View {
    @StateObject var UserData: CoreData
    @EnvironmentObject var ClassName: ClassNameData
    @State var showVerifyAlert = false
    @State var isVerified = false
    @State var timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
    @State var selection: Int? = 0
    @Binding var showWarning: Bool
    @State var errorStr = ""
    @State var allowBLE = false
    @State var showError = false
    @State var showSetting = false
    @State var showBLEGuide = false
    @State var isLoaded = false
    @State var once = false
    @State var timeOut = 0
    @State var UIAController = UIAlertController()
    @Environment(\.colorScheme) var _Color: ColorScheme
    @State var delegate: MyCBPeripheralManagerDelegate?
    @State var transferCharacteristic: CBMutableCharacteristic? = nil
    
    var body: some View {
        DispatchQueue.main.async {
            if !once {
                once = true
                connect()
                
                
                //MARK: Find BLEName
                for idx in 0..<ClassName.ClassName.count {
                    if ClassName.ClassName[idx].name == UserData.classNameStr {
                        BLEName = ClassName.ClassName[idx].BLEName ?? ""
                        break
                    }
                }
                if BLEName != "" {
                    self.delegate = MyCBPeripheralManagerDelegate()
                    UserDefaults.standard.set(true, forKey: "BLE.configured")
                }
                else {
                    UserDefaults.standard.set(false, forKey: "BLE.configured")
                }
                allowBLE = BLEName != ""
            }
        }
        return ZStack {
            VStack {
                if isLoaded {
                    HomeView(isVerified: self.$isVerified).environmentObject(UserData)
                        .navigationBarBackButtonHidden(true)
                        .navigationBarItems(leading: HStack {
                            Image(systemName: "gearshape.fill")
                                .imageScale(.large)
                                .foregroundColor(.blue)
                                .onTapGesture {
                                    RunAfterVierified
                                    {self.showSetting = true}
                                }
                                .sheet(isPresented: self.$showSetting, content: {
                                    NavigationView {
                                        SettingsView(showCloseButton: true)
                                    }.navigationViewStyle(StackNavigationViewStyle())
                                })
                            Image(systemName: allowBLE ? "wave.3.left.circle.fill":"wave.3.left.circle")
                                .imageScale(.large)
                                .foregroundColor(.blue)
                                .onTapGesture {
                                    RunAfterVierified {
                                        self.showBLEGuide = true
                                    }
                                }
                                .sheet(isPresented: self.$showBLEGuide) {
                                    BLEGuideView(classNameStr: self.UserData.classNameStr)
                                        .environmentObject(self.UserData)
                                }
                        })
                }
                else {
                    HStack {
                        Text("正在加载...")
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                    }
                }
            }
            .background(SUIAController(showAlert: $showError, $UIAController))
            .onReceive(timer) { _ in
                self.showWarning = UserData.FILE_PROVIDER_IS_UPLOADING_FLAG
                // print(UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG)
                if UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                    timeOut += 1
                }
                if timeOut == 2 {
                    timeOut = 0
                    connect()
                }
                if !UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                    self.isLoaded = true
                    connect()
                    if let error = UserData.fileProviderError {
                        UserData.fileProviderError = nil
                        let error = error as NSError
                        // print("errorCode: \(error.code)\n----------\n")
                        self.errorStr = error.localizedDescription + "\nPlease reopen the app or contact with your adiministrator for further help."
                        self.timer = Timer.TimerPublisher(interval: 120, runLoop: .current, mode: .default).autoconnect()
                        UIAController = UIAlertController(title: "网络错误", message: errorStr, preferredStyle: .alert)
                        UIAController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
                        UIAController.addAction(UIAlertAction(title: "重试", style: .destructive, handler: { _ in
                            self.timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
                        }))
                        self.showError = true
                    }
                }
            }
//            if showWarning {
//                VStack {
//                    Spacer()
//                    IsUploadingWarning(showWarning: self.$showWarning)
//                }
//            }
        }
    }
    private func connect() {
        withAnimation(.easeInOut(duration: 0.5)) {
            if UserData.downloadDataByHttp() {}
        }
    }
}
